package cn.com.connected.base.validate;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Collection;
import java.util.Iterator;

/**
 *
 * @apiNote 自定义注解逻辑实现
 * @version 3.0.0
 *
 */
public class PatternListValidator implements ConstraintValidator<ListStringPattern, Collection> {

    private String pattern;
    private String message;

    @Override
    public void initialize(ListStringPattern constraintAnnotation) {
        this.pattern = constraintAnnotation.regexp();
        this.message = constraintAnnotation.message();
    }

    @Override
    public boolean isValid(Collection collection, ConstraintValidatorContext constraintValidatorContext) {
        if (CollectionUtils.isEmpty(collection)){
            // 为空不做校验 请额外使用其他注解 如：@NotNull
            return true;
        }

        Iterator<String> texts = collection.iterator();
        while (texts.hasNext()) {
            String string = texts.next();
            if (!string.matches(pattern)) {
                return false;
            }
        }
        return true;
    }
}